package com.sdry.web.controller.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageInfo;
import com.sdry.entity.SysRole;
import com.sdry.service.SysRoleService;
import com.sdry.utils.ResponseUtil;

import net.sf.json.JSONObject;

@RequestMapping(value="/sysRole")
@Controller
public class SysRoleController {

	@Resource
	private SysRoleService sysRoleService;
	
	@RequestMapping(value="/listPageRole")
	public void listPageRole(@RequestParam(value = "limit",required = false)int limit,
            @RequestParam(value = "offset",required = false)int offset
            ,SysRole sysRole,HttpServletResponse response) throws Exception{
		Map<String, Object> map = new HashMap<>();
		map.put("pageSize", limit);
		map.put("page", offset);
		if (sysRole.getRoleName() != null) {
			map.put("roleName", sysRole.getRoleName());
		} else {
			map.put("roleName", "");
			sysRole.setRoleName("");
		}
		List<SysRole> sysRoleList = sysRoleService.listPageRole(map);
		PageInfo<SysRole> info = new PageInfo<SysRole>(sysRoleList);
    	
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total", info.getTotal());
        jsonObject.put("rows", info.getList());
        ResponseUtil.write(response, jsonObject);
	}
	
	@RequestMapping(value="/saveRole")
	public void saveRole(SysRole sysRole,HttpServletResponse response) throws IOException{
		int isSuccess = 0;
		if (sysRole.getRoleID() == null || "".equals(sysRole.getRoleID())) {
			int count = sysRoleService.findCountByName(sysRole);
			if (count > 0) {
				isSuccess = -1;
			} else {
				isSuccess = sysRoleService.insertRole(sysRole);
			}
		} else {
			isSuccess = sysRoleService.updateRole(sysRole);
		}
		if (isSuccess == 1) {
			response.getWriter().print("1");
		} else if (isSuccess == 0) {
			response.getWriter().print("0");
		} else {
			response.getWriter().print("2");
		}
	}
	
	/**
	 * 多删除
	 * @param ids 角色id累加字符串
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteRole")
	public void deleteRole(String ids,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		int isSuceess = 0;
		String[] roleIDs = ids.split(",");
		for (int i = 0; i < roleIDs.length; i++) {
			isSuceess = sysRoleService.deleteRole(Long.parseLong(roleIDs[i]));
		}
		if (isSuceess >= 1) {
			response.getWriter().print("1");
		}else{
			response.getWriter().print("0");
		}
	}
}
